package io.scnb.lesson001.demo24.test6;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CostTimeProxy implements MethodInterceptor {
    // 目标对象
    private Object target;

    public CostTimeProxy(Object target) {
        this.target = target;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        long start = System.nanoTime();
        Object result = methodProxy.invokeSuper(o, objects);
        long end = System.nanoTime();
        System.out.println(method + ", 耗时(纳秒):" + (end - start));
        return result;
    }

    /**
     * 创建任意类的代理对象
     */
    public static <T> T createProxy(T target) {
        io.scnb.lesson001.demo17.CostTimeProxy costTimeProxy = new io.scnb.lesson001.demo17.CostTimeProxy(target);
        Enhancer enhancer = new Enhancer();
        enhancer.setCallback(costTimeProxy);
        enhancer.setSuperclass(target.getClass());
        return (T) enhancer.create();
    }
}
